package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.UserMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Utils;
import com.example.forum.utils.StringUtils;
import com.example.forum.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service //加入Spring
@Slf4j
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 根据名字查询用户信息
     * @param username
     * @return
     */
    @Override
    public User selectByName(String username) {
        //非空校验
        if(StringUtils.isEmpty(username)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //在数据库中根据用户名查询用户信息
        User user = userMapper.selectByName(username);
        //返回结果
        return user;
    }

    /**
     * 根据用户id查询用户信息
     * @param id
     * @return
     */
    @Override
    public User selectById(Long id) {
        //非空校验
        if(id==null || id<0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用DAO
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    /**
     * 注册用户
     * @param user
     */
    @Override
    public void createNormalUser(User user) {
        if(user==null || StringUtils.isEmpty(user.getUsername())
        || StringUtils.isEmpty(user.getNickname()) || StringUtils.isEmpty(user.getPassword())
        || StringUtils.isEmpty(user.getSalt())){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户名是否存在
        User existsUser = selectByName(user.getUsername());
        if(existsUser != null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //为属性设置默认值
        if(user.getGender() != null){
            if(user.getGender()<0 || user.getGender()>2){
                user.setGender((byte) 2);
            }
        }else{
            user.setGender((byte) 2);
        }
        //发帖数
        user.setArticleCount(0);
        //是否管理员
        user.setIsAdmin((byte) 0);
        //状态
        user.setState((byte) 0);
        //是否删除
        user.setDeleteState((byte) 0);
        //时间
        Date date=new Date();
        //创建时间
        user.setCreateTime(date);
        //更新时间
        user.setUpdateTime(date);

        //写入数据库
        int row = userMapper.insertSelective(user);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString()+"注册用户失败，username="+user.getUsername());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        //非空校验
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据用户名查询用户信息
        User user = selectByName(username);
        //校验用户是否存在
        if(user == null){
            //打印日志
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString()+",username="+username);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //校验密码是否正确
        String encryptPassword= MD5Utils.md5Salt(password,user.getSalt());
        if(!encryptPassword.equalsIgnoreCase(user.getPassword())){
            //打印日志
            log.info("密码输入错误，username="+username+",password="+password);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }
        //返回用户信息
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        //非空校验
        if(id==null || id<0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询现有的用户信息
        User user=selectById(id);
        //校验用户是否为空
        if(user == null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //构造更新对象
        User updateUser=new User();
        updateUser.setId(user.getId());  //用户id
        updateUser.setArticleCount(user.getArticleCount()+1);  //帖子数量＋1
        updateUser.setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        //非空校验
        if(id==null || id<0){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //查询现有的用户信息
        User user=selectById(id);
        //校验用户是否为空
        if(user == null){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }
        //构造更新对象
        User updateUser=new User();
        updateUser.setId(user.getId());  //用户id
        updateUser.setArticleCount(user.getArticleCount()-1);  //帖子数量-1
        updateUser.setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //非空校验
        if(user==null){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验User对象
        User existsUser=selectById(user.getId());
        if(existsUser==null || existsUser.getDeleteState()==1){
            //用户不存在
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }


        //定义一个标识
        boolean checkParam=false;
        //定义要更新的对象
        User updateUser=new User();
        //设置id
        updateUser.setId(user.getId());
        //用户名
        //参数校验
        if(!StringUtils.isEmpty(user.getUsername())){
            //更新用户登录的用户名，这个用户名是唯一键
            User checkUser=selectByName(user.getUsername());
            //校验用户名是否存在
            if(checkUser!=null){
                //已存在
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }
            //不存在
            updateUser.setUsername(user.getUsername());
            //更新标识
            checkParam=true;
        }

        //昵称
        if(!StringUtils.isEmpty(user.getNickname())){
            //更新昵称
            updateUser.setNickname(user.getNickname());
            //更新标识
            checkParam=true;
        }

        //性别
        if(user.getGender() !=null ){
            //设置性别
            updateUser.setGender(user.getGender());
            //校验性别有效性
            if(updateUser.getGender()<0 || updateUser.getGender()>2){
                //处理方式1：无效，将性别设置成默认值
                //处理方式2：设置为null，表示保持原来的性别，不更新数据库
                updateUser.setGender((byte) 2);

            }
            //更新标识
            checkParam=true;
        }

        //电话号码
        if(!StringUtils.isEmpty(user.getPhoneNum())){
            //设置电话
            updateUser.setPhoneNum(user.getPhoneNum());
            //更新标识
            checkParam=true;
        }

        //邮箱
        if(!StringUtils.isEmpty(user.getEmail())){
            //设置电话
            updateUser.setEmail(user.getEmail());
            //更新标识
            checkParam=true;
        }

        //电话号码
        if(!StringUtils.isEmpty(user.getRemark())){
            //设置电话
            updateUser.setRemark(user.getRemark());
            //更新标识
            checkParam=true;
        }

        //判断参数标识是否检查通过
        if(checkParam==false){
            //不通过
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS)+"所有参数不能同时为空");
        }
        //调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    //修改密码
    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        //非空校验
        if(id==null || id<=0 || StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(oldPassword)){
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //根据id查询用户信息
        User user = selectById(id);
        if(user==null || user.getDeleteState()==1){
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"user id="+id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验老密码是否正确
        String encryptOldPassword=MD5Utils.md5Salt(oldPassword,user.getSalt());
        if(!encryptOldPassword.equalsIgnoreCase(user.getPassword())){
            //打印日志
            log.warn(ResultCode.FAILED_PASSWORD_CHECK.toString()+"user id="+id+"oldPassword="+oldPassword);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PASSWORD_CHECK));
        }
        //生成新密码
        String salt= UUIDUtils.UUID_32();
        String encryptPassword=MD5Utils.md5Salt(newPassword,salt);

        //构造更新对象
        User updateUser=new User();
        updateUser.setId(id);
        updateUser.setPassword(encryptPassword);
        updateUser.setSalt(salt);
        updateUser.setUpdateTime(new Date());

        //调用DAO
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row!=1){
            //打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public int updateArticleCountById(Long id) {
        return 0;
    }
}
